import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:furaha_mkopo/commonTool/fm_screen_tool.dart';
import 'package:furaha_mkopo/commonTool/fm_time_tool.dart';
import 'package:furaha_mkopo/commonUI/fm_custon_nav_bar_widget.dart';
import 'package:furaha_mkopo/net/fm_net_param_manager.dart';
import 'package:furaha_mkopo/page/base/fm_base_page_widget.dart';
import 'package:geolocator_platform_interface/src/models/position.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../home/controller/fm_common_controller.dart';
import 'fm_web_controller.dart';

class FMWebWidget extends FMBasePageWidget {

  final String url;
  final String listen;
  final bool? isOldPage;
  const FMWebWidget({super.key,required this.url,required this.listen,this.isOldPage});

  @override
  State<FMWebWidget> createState() => _FMWebWidgetState();
}

class _FMWebWidgetState extends FMBasePageState<FMWebWidget> {

  double loadingPercentage = 0;

  WebViewController? _webViewController;

  String title = "";

  final controller = Get.put(FMWebController());

  @override
  void initState() {
    super.initState();
    initWebController();

    String url = FMNetParamManager().getWebUrlPath(widget.url);
    _webViewController?.loadRequest(Uri.parse(url));
  }

  @override
  void dispose() {
    Get.delete<FMWebController>();
    super.dispose();
  }

  void initWebController() {
    _webViewController = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(Colors.transparent)
      ..setNavigationDelegate(
          NavigationDelegate(
            onProgress: (int progress) {
              setState(() {
                loadingPercentage = progress / 100;
              });
            },
            onPageStarted: (String url) {
              setState(() {
                loadingPercentage = 0.0;
              });
            },
            onPageFinished: (String url) async {
              String pageTitle = await _webViewController?.getTitle() ?? "Furaha Mkopo";
              setState(() {
                loadingPercentage = 1.0;
                title = pageTitle.isEmpty ? "Furaha Mkopo" : pageTitle;
              });
            },
          )
      );
    _webViewController?.addJavaScriptChannel("wanted", onMessageReceived: (JavaScriptMessage message){
        controller.back(context);
    });
    _webViewController?.addJavaScriptChannel("speak", onMessageReceived: (JavaScriptMessage message){
      controller.jumpWidget(context,message.message);
    });
    _webViewController?.addJavaScriptChannel("people", onMessageReceived: (JavaScriptMessage message){
      controller.backToHome(context);
    });
    _webViewController?.addJavaScriptChannel("madame", onMessageReceived: (JavaScriptMessage message){
      controller.showSKStoreReview();
    });
    _webViewController?.addJavaScriptChannel("rail", onMessageReceived: (JavaScriptMessage message){
      controller.addMobState(message.message);
    });
    _webViewController?.addJavaScriptChannel("balloch", onMessageReceived: (JavaScriptMessage message){
      controller.startTime = FMTimeTool.currentTime;
    });
    _webViewController?.addJavaScriptChannel("walked", onMessageReceived: (JavaScriptMessage message){
      controller.endBindingCard();

      if (widget.isOldPage == true) {
        Navigator.pop(context);
        return;
      }

      Get.find<FMCommonController>().onRequestGoOught(context, widget.listen);
    });
  }

  @override
  Widget build(BuildContext context) {
      return Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Colors.white,
        body: Column(
          children: [
            SizedBox(height: FMScreenTool.topPadding(context)),
            FMCustomNavBarWidget(title:title),
            progressIndicator(),
            Expanded(
              child: WebViewWidget(

                 controller: _webViewController!
              )
            )
          ],
        ),
      );
  }

  @override
  void onLocationError(String error) {

  }

  @override
  void onLocationUpdated(Position position) {
    controller.position = position;
    Get.find<FMCommonController>().position = position;
  }

  Widget progressIndicator() {
    if (loadingPercentage < 1) {
      return SizedBox(
        height: 2,
        child: LinearProgressIndicator(
          value: loadingPercentage,
        ),
      );
    }
    return Container();
  }
}
